const { RSA_NO_PADDING } = require("constants");
let express = require("express");
let router = express.Router();
let fs = require("fs");
let pathLib = require("path");
let mgdb = require("../../utils/mgdb");

//管理端结果，返数据动作，前端渲染

//增加库
router.post("/", (req, res, next) => {
  //抓取参数
  let { title_w, title, zuozhe, main, fabushijian } = req.body;
  let time = Date.now();
  // 设置imgUrl的路径 和随机后缀名称
  let imgUrl;
  req.files &&
    req.files.forEach((file, index) => {
      imgUrl =
        "/upload/news_message/" +
        file.filename +
        pathLib.parse(file.originalname).ext;
      fs.renameSync(
        file.path,
        file.path + pathLib.parse(file.originalname).ext
      );
    });
  // 设置为当前参数为必传参数
  // if (!title) {
  //   res.send({ err: 1, msg: "title标题为必传参数" });
  //   return;
  // } else if (!zuozhe) {
  //   res.send({ err: 1, msg: "文章作者为必传参数" });
  //   return;
  // } else if (!main) {
  //   res.send({ err: 1, msg: "发布内容为必传参数" });
  //   return;
  // }

  //开库，写入   caselist
  mgdb
    .open({ collectionName: "news_message" })
    .then(({ collection, client }) => {
      //插入
      let data = { title, title_w, zuozhe, main, fabushijian, imgUrl };
      collection.insertOne(data, (err, result) => {
        if (!err && result.result.n > 0) {
          res.send({
            err: 0,
            msg: "成功",
            data: {
              _id: result.insertedId,
              ...data, //解构
            },
          });
        } else {
          res.send({ err: 1, msg: "添加失败" });
        }
        client.close();
      });
    });
});

//删除库
router.delete("/:_id", (req, res, next) => {
  let _id = req.params._id;
  if (!_id) {
    res.send({ err: 1, msg: "_id为必传参" });
    return;
  }
  mgdb
    .open({ collectionName: "news_message" })
    .then(({ collection, client, ObjectId }) => {
      collection.deleteOne({ _id: ObjectId(_id) }, (err, result) => {
        if (!err && result.result.n > 0) {
          res.send({ err: 0, msg: "删除成功" });
        } else {
          res.send({ err: 0, msg: "删除失败" });
        }
        client.close();
      });
    });
});

//修改库
router.patch("/:_id", (req, res, next) => {
  let _id = req.params._id;
  if (!_id) {
    res.send({ err: 1, msg: "_id为必传参" });
    return;
  }
  mgdb
    .open({ collectionName: "news" })
    .then(({ collection, client, ObjectId }) => {
      //查询到所有key 和 客户端传入的key 合并，删除更新前的文件
      collection.find({ _id: ObjectId(_id) }).toArray((err, result) => {
        if (!err && result.length > 0) {
          //整理要合并的数据
          let { title, zuozhe, main, fabushijian, title_w, imgUrl } = req.body;
          title = title || result[0].title;
          title_w = title_w || result[0].title_w;
          zuozhe = zuozhe || result[0].zuozhe;
          main = main || result[0].main;
          fabushijian = fabushijian || result[0].fabushijian;
          imgUrl = imgUrl || result[0].imgUrl;

          // let imgUrl;
          req.files &&
            req.files.forEach((file, index) => {
              imgUrl =
                "/upload/news_message/" +
                file.filename +
                pathLib.parse(file.originalname).ext;
              //删除以前  result[0].detail.auth_icon   -> res.unlink
              fs.renameSync(
                file.path,
                file.path + pathLib.parse(file.originalname).ext
              );
            });

          imgUrl = imgUrl || result[0].imgUrl;
          //修改
          collection.updateOne(
            {
              _id: ObjectId(_id),
            },
            {
              $set: {
                title,
                title_w,
                zuozhe,
                main,
                fabushijian,
                imgUrl,
              },
            },
            (err, result) => {
              if (!err && result.result.n > 0) {
                res.send({ err: 0, msg: "修改成功" });
              } else {
                res.send({ err: 1, msg: "修改失败" });
              }
              client.close();
            }
          );
        } else {
          res.send({ err: 0, msg: "修改失败,数据不存在，傻笑重时" });
        }
      });
    });
});

//查排 调用api接口
// localhost:3000/api/list/caselist/
router.get("/", (req, res, next) => {});
module.exports = router;
